# -*- coding:utf-8 -*-
#from musiccrawler.xiami.xiamihot import getallmusic
from musiclib.musiccrawler.xiami.xiamihot import getallmusic
from musiclib.musiccrawler.googlemusic.getallurl import getfirstsong
from musiclib.models import Music

from django.http import HttpResponse
from django.shortcuts import render_to_response,redirect

import simplejson
import logging

def addonemusic(request):
    dic = {}
    #check shrekwang first,write to a function
    
    #get the songname

    #check conflict with current songs

    return HttpResponse(simplejson.dumps(dic))

def addbatmusic(request):
    #add several songs
    dic = {}

    return HttpResponse(simplejson.dumps(dic))


def mudbcrawler(request):
    """
    check admin how to in a neat way?
    """
    musics = getallmusic()
    for music in musics:
        c = Music.all().fitler('mname =',musics['mname']).count()
        if c == 0:
            tmpm = Music()
            tmpm.mname = music['manme']
            tmpdic = {}
            tmpdic['xiamiid'] = music['mid']
            tmpm.jsondesp = simplejson.dumps(tmpdic)
            tmpm.save()
        elif c > 1:
            logging.error("a name corresponse to more than a song")
    dic = {}
    dic['status'] = "1"
    return HttpResponse(simplejson.dumps(dic))

def getGoogleInfobyStr(request):
    searchstr = request.GET['searchstr']
    searchstr = searchstr.replace(" ","%20")
    curdic = {}

    try:
        thesong = getfirstsong(searchstr)
        thesong.load_download()
        mp3url = getattr(thesong,"downloadUrl")
        thesong.lyric_load_download()
        lyricurl =  getattr(thesong,"lyricdownloadUrl")
        curdic['googleid'] = getattr(thesong,"id")
        curdic['mp3url'] = mp3url
        curdic['lyricurl'] = lyricurl
        return HttpResponse(simplejson.dumps(curdic))
    except Exception,e:
        curdic['failed'] = 1
        curdic['errmsg'] = str(e)
        return HttpResponse(simplejson.dumps(curdic))    
